package cn.blossoming.controller.web;

import cn.blossoming.controller.exception.WebException;
import cn.blossoming.controller.vo.ApiResult;
import cn.blossoming.controller.vo.user.UserVo;
import cn.blossoming.service.base.consts.RedisKeys;
import cn.blossoming.service.base.utils.SmsUtils;
import cn.blossoming.service.base.utils.ValidationUtils;
import cn.blossoming.service.user.UserService;
import cn.blossoming.service.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

import static cn.blossoming.service.base.consts.SessionConst.SESSION_USER;

@RestController
@RequestMapping(path = "/account", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AccountController extends BaseController {

    private StringRedisTemplate redisTemplate;
    private ValueOperations<String, String> valueOperations;
    private HashOperations<String, String, String> hashOperations;
    @Autowired
    private UserService userService;

    @Autowired
    public void setRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.redisTemplate = stringRedisTemplate;
        this.hashOperations = stringRedisTemplate.opsForHash();
        this.valueOperations = stringRedisTemplate.opsForValue();
    }

    /**
     * 获取验证码
     * 15分钟失效
     *
     * @param phone 手机号
     */
    @GetMapping(path = "/{phone}/verification/")
    public ApiResult<?> getVerificationCode(@PathVariable String phone) {
        if (!ValidationUtils.checkPhone(phone))
            throw new WebException(101, "非法手机号");
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        SmsUtils.sendVerificationCode(phone, code);
        valueOperations.set(RedisKeys.verificationPhone(phone), code);
        redisTemplate.expire(RedisKeys.verificationPhone(phone), 15, TimeUnit.MINUTES);
        return ApiResult.builder(null);
    }

    /**
     * 登入
     *
     * @param phone 手机号
     * @param code  验证码
     */
    @GetMapping(path = "/{phone}/verification/{code}")
    public ApiResult<UserVo> checkPhoneCode(@PathVariable String phone, @PathVariable String code, HttpSession session) {
        //if (!ValidationUtils.checkPhone(phone))
        //    throw new WebException(101, "非法手机号");
        //String codeTrue = valueOperations.get(RedisKeys.verificationPhone(phone));
        //if (!code.equals(codeTrue))
        //    throw new WebException(103, "验证码错误");

        User user = userService.getUserByPhone(phone);
        session.setAttribute(SESSION_USER, user);
        UserVo userVo = new UserVo();
        userVo.setUser(user);
        userVo.setToken(session.getId());

        String onlyUserHashKey = RedisKeys.getOnlyUserHashKey(user.getId());
        String springSessionKey = hashOperations.get(RedisKeys.ONLY_USER_KEY, onlyUserHashKey);
        if(springSessionKey!=null) {
            hashOperations.delete(RedisKeys.ONLY_USER_KEY, onlyUserHashKey);
            redisTemplate.delete(redisTemplate.keys(String.format("*%s*", springSessionKey)));
        }
        hashOperations.put(RedisKeys.ONLY_USER_KEY, onlyUserHashKey, session.getId());
        return ApiResult.builder(userVo);
    }
}
